package api;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;

import org.jdom.*;

/**
 * @author 		xthsky
 * @created on	2009年2月21日, 下午5:22
 * @description	为api提供xml格式的结果
 */
public class ResultXml {
	
	public ResultXml(){

	}
	
	public static <T> Document getXml(T t)
			throws IntrospectionException, IllegalAccessException,
			InvocationTargetException{
		
		Element root = new Element("root");
        Document document = new Document(root);

		root.addContent(newElement(t));
		
        return document;
	}

	public static <T> Element newElement(T t)
			throws IntrospectionException, IllegalAccessException,
			InvocationTargetException{
		if(t == null) return null;
		Element elements = new Element(t.getClass().getSimpleName().toLowerCase());
		System.out.println(t.getClass().getSimpleName().toLowerCase());
		
		BeanInfo beanInfo = Introspector.getBeanInfo(t.getClass()); // 获取类属性
		for (PropertyDescriptor descriptor : beanInfo.getPropertyDescriptors()) {
			String propertyName = descriptor.getName();
			String propertyType = descriptor.getPropertyType().getSimpleName();
			
			//temp code--start
			System.out.println(propertyName+","+propertyType);
			if(propertyType.equals("Node"))
				continue;
			//temp code--end
			
			Object propertyObject = descriptor.getReadMethod().invoke(t);

			if(propertyObject == null ||propertyName.equals("class")||propertyName.equals("sight")||propertyName.equals("user"))
				continue;
			else if(propertyType.equals("String")||propertyType.equals("Date")||propertyType.equals("Long")||propertyType.equals("Integer")||propertyType.equals("int")){
				// 下面一句可以 try 起来，这样当一个属性赋值失败的时候就不会影响其他属性赋值。
				try{
					String propertyValue = descriptor.getReadMethod().invoke(t).toString();
					if(propertyName.equals("name")||propertyName.equals("description"))
						elements.addContent(new Element(propertyName).setText(propertyValue));
					else
						elements.setAttribute(propertyName, propertyValue);
				}
				catch(Exception ex) {
					//e.printStackTrace();
				}
			}
			else if(propertyType.equals("ArrayList")){
				Element e = new Element(propertyName);
				for(Object o : (ArrayList)propertyObject){
					e.addContent(newElement(o));
				}
				elements.addContent(e);
			}
			else {
				elements.addContent(newElement(propertyObject));
			}
		}
		return elements;
	}
	
}
